//
//  XiuGaiXinXiViewController.m
//  FactorySale
//
//  Created by 李 on 2020/1/15.
//  Copyright © 2020 主事丫环. All rights reserved.
//

#import "XiuGaiXinXiViewController.h"
#import "NetLoadAreaPickerViewController.h"
#import "LoginViewController.h"
#import "ZhuCeSuccessedAlertView.h"
#import "ShenHeZhongViewController.h"
#import "XiuGaiXinXiCell.h"
#import <UIButton+WebCache.h>

@interface XiuGaiXinXiViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
//列表
@property (nonatomic,strong) UITableView *listTableView;
@property (nonatomic,strong)NSString *shengshiquString;
@property (nonatomic,strong)NSString *shengshiquCode;

@property (nonatomic,strong)NSString *factory_name;
@property (nonatomic,strong)NSString *factory_person;
@property (nonatomic,strong)NSString *factory_phone;
@property (nonatomic,strong)NSString *yzCode;
@property (nonatomic,strong)NSString *factory_email;
@property (nonatomic,strong)NSString *factory_area;
@property (nonatomic,strong)NSString *factory_address;
@property (nonatomic,strong)NSString *detailAddress;//省市区 加详细地址

@property(nonatomic,strong)UIImage *zhiZhaoImage;
@property(nonatomic,strong)NSString *zhiZhaoNetworkImg;

@property(nonatomic,assign)BOOL zhiZhaoSelected;

@property(nonatomic,strong)ZhuCeSuccessedAlertView *alert;

@end
static NSString *const XiuGaiXinXiCellID = @"XiuGaiXinXiCell";

@implementation XiuGaiXinXiViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];

    
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage imageNamed:@"顶部渐变"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forBarMetrics:UIBarMetricsDefault];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"注册信息";
    [self.leftbutton setImage:imgname(@"left_icon") forState:(UIControlStateNormal)];
    [self configViews];
    [self reloadViewsData];
}
-(void)reloadViewsData
{
    self.factory_name = self.resultDic[@"factory_name"];
   self.factory_person= self.resultDic[@"factory_person"];
      self.factory_phone= self.resultDic[@"factory_phone"];
     self.factory_email= self.resultDic[@"factory_email"];
    
    self.shengshiquCode = self.resultDic[@"factory_area"];
    self.zhiZhaoNetworkImg  = self.resultDic[@"factory_licence"];
    NSArray *array = [self.resultDic[@"factory_address"] componentsSeparatedByString:@" "];
    
    self.shengshiquString = array[0]; //省市区
    self.factory_address = array[1]; //详细地址
    [self.listTableView reloadData];
}
-(void)configViews
{
       [self.listTableView registerNib:[UINib nibWithNibName:NSStringFromClass([XiuGaiXinXiCell class]) bundle:nil] forCellReuseIdentifier:XiuGaiXinXiCellID];
       [self.view addSubview:self.listTableView];
}
- (UITableView *)listTableView
{
    if (!_listTableView) {
        _listTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, SCREEN_HEIGHT-kNaviHeight-TabbarSafeBottomMargin) style:UITableViewStylePlain];
        _listTableView.hidden = NO;
        _listTableView.delegate = self;
        _listTableView.dataSource = self;
        _listTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        _listTableView.estimatedSectionHeaderHeight = 0;
        _listTableView.estimatedSectionFooterHeight = 0;
        _listTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
    }
    return _listTableView;
}
#pragma mark UITableView

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
  
   return 0.01;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 1;
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        XiuGaiXinXiCell *cell = [tableView dequeueReusableCellWithIdentifier:XiuGaiXinXiCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
       UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(diQuBtnClick)];
        [cell.shengShiQuTF addGestureRecognizer:tap];
        cell.shengShiQuTF.userInteractionEnabled = YES;
       
        cell.shengShiQuTF.text = self.shengshiquString;
    
       cell.changJiaNameTF.text = self.factory_name;
       cell.lianXiRenTF.text = self.factory_person;
       cell.phoneTF.text = self.factory_phone;
       cell.emailTF.text = self.factory_email;
       cell.xiangXiDiZhiTF.text = self.factory_address;
    
    if (self.zhiZhaoImage) {
        [cell.zhiZhaoBtn setImage:self.zhiZhaoImage forState:UIControlStateNormal];

    }else
    {
         [cell.zhiZhaoBtn sd_setImageWithURL:[NSURL URLWithString:self.zhiZhaoNetworkImg] forState:UIControlStateNormal];
    }
    
      [cell.zhiZhaoBtn addTarget:self action:@selector(seleImage) forControlEvents:UIControlEventTouchUpInside];
      [cell.commitBtn addTarget:self action:@selector(commitBtnClick) forControlEvents:UIControlEventTouchUpInside];
   
    [cell.sendCodeButton addTarget:self action:@selector(sendCodeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
   
   
    
    cell.changJiaNameTFEndHandle = ^(NSString * _Nonnull text) {
        self.factory_name = text;
    };
    cell.lianXiRenTFEndHandle = ^(NSString * _Nonnull text) {
        self.factory_person = text;
    };
    cell.phoneTFEndHandle = ^(NSString * _Nonnull text) {
        self.factory_phone = text;
    };
    cell.yanZhengMaTFEndHandle  = ^(NSString * _Nonnull text) {
            self.yzCode = text;
       };
    cell.emailTFEndHandle = ^(NSString * _Nonnull text) {
        self.factory_email = text;
    };
    cell.xiangXiDiZhiTFEndHandle = ^(NSString * _Nonnull text) {
         self.factory_address = text;
    };
        return cell;
  
}
-(void)sendCodeButtonClick:(LMCountDownButton *)sender {
    //去除字符串中空格
    self.factory_phone = [self.factory_phone stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (![self isMobileNumberOnly:self.factory_phone]) {
        ShowToastWithText(@"请输入正确电话号码");
        return;
    }
    NSDictionary *dic = @{@"phone":self.factory_phone};
    [MBProgressHUD showHUDAddedTo:self.view  animated:YES];

    [NetWorkTool POST:sendMsg param:[dic mutableCopy] success:^(id dic) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [sender startCountDown];
        ShowToastWithText(@"验证码发送成功");
    } other:^(id dic) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];

    } fail:^(NSError *error) {

        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } needUser:NO];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return 636;
}
-(void)diQuBtnClick
{
    NetLoadAreaPickerViewController * loadAreaVC = [[NetLoadAreaPickerViewController alloc]init];
    kWeakSelf;
    loadAreaVC.selectedBlock = ^(NetLoadAreaModel *areaModel) {
        KMyLog(@"选中的地址%@",areaModel);
        self.shengshiquString = [NSString stringWithFormat:@"%@%@%@", areaModel.provinceName, areaModel.cityName, areaModel.districtName];
        //省市区 code拼接
        self.shengshiquCode = [NSString stringWithFormat:@"%@",areaModel.districtCode];
        [weakSelf.listTableView reloadData];
    };
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) {
        loadAreaVC.modalPresentationStyle=UIModalPresentationOverCurrentContext;
    } else {
        loadAreaVC.modalPresentationStyle=UIModalPresentationCurrentContext;
    }
    [self presentViewController:loadAreaVC animated:NO completion:^{
        
    }];
    return;
}
-(void)seleImage{
    UIImagePickerController *pick = [[UIImagePickerController alloc]init];
    pick.allowsEditing = YES;
    pick.delegate = self;
    [UIAlertController showPhotoAlerControllerPicker:pick controller:self sourceView:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *image = info[UIImagePickerControllerEditedImage];
     self.zhiZhaoImage = image;
    self.zhiZhaoSelected = YES;
    [self.listTableView reloadData];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
//提交
- (void)commitBtnClick
{
    
    self.detailAddress = [NSString stringWithFormat:@"%@ %@",self.shengshiquString,self.factory_address];

    if (self.factory_name.length ==0) {
        ShowToastWithText(@"请输入厂家名称");
        return;
    }
    if (self.factory_person.length ==0) {
           ShowToastWithText(@"请输入联系人");
            return;
       }
    if (self.factory_phone.length ==0) {
           ShowToastWithText(@"请输入手机号");
            return;
       }else
       {
           if (![self isMobileNumberOnly:self.factory_phone]) {
                  ShowToastWithText(@"请输入正确的手机号");
                  return;
              }
       }
    if (self.factory_email.length ==0) {
           ShowToastWithText(@"请输入邮箱");
            return;
       }else
       {
           if (![HFTools isValidateEmail:self.factory_email]) {
                          ShowToastWithText(@"请输入正确的电子邮箱");
                          return;
                      }
       }
    if (self.shengshiquCode.length ==0) {
        ShowToastWithText(@"请选择省市区");
        return;
    }
    if (self.detailAddress.length ==0) {
        ShowToastWithText(@"请输入详细地址");
        return;
    }
    if (self.zhiZhaoSelected ==NO) {
          ShowToastWithText(@"请上传营业执照");
          return;
    }
    NSDictionary *param = @{@"factory_name":NOTNIL(self.factory_name),
                          @"factory_person":NOTNIL(self.factory_person),
                          @"factory_phone":NOTNIL(self.factory_phone),
                            @"factory_email":NOTNIL(self.factory_email),
                          @"factory_area":NOTNIL(self.shengshiquCode),//    所在区域（县级代码）
                          @"factory_address":NOTNIL(self.detailAddress),//详细地址（拼接上 省市县 +详细地址）
                            
    };
    NSString *json = [HFTools toJSONString:param];
    NSMutableDictionary *allDic = [NSMutableDictionary dictionaryWithCapacity:1];
    allDic[@"data"] = json;
  
    [MBProgressHUD showHUDAddedTo:self.view  animated:YES];

    [NetWorkTool UploadPicWithUrl:updateFactoryUserByPhone param:allDic key:@"licenceImg" image:self.zhiZhaoImage withSuccess:^(id dic) {
       
        [self.navigationController popToRootViewControllerAnimated:YES];
      
    } failure:^(NSError *error) {
        [MBProgressHUD  hideHUDForView:self.view animated:YES];
    }];
    
}
//判断是否为电话号码
- (BOOL)isMobileNumberOnly:(NSString *)mobileNum {
    
    NSString * MOBILE = @"^((10[0-9])|(11[0-9])|(12[0-9])|(13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    if ([regextestmobile evaluateWithObject:mobileNum] == YES) {
        return YES;
    } else {
        return NO;
    }
}
@end
